package com.leetcode.No0904;

import org.junit.Test;

/**
 * @program: Solution
 * @description: 水果成篮
 * @author: Wang Zhihua
 * @date: 2022-10-19
 */
public class Solution {

    int[] fruits;

    public int totalFruit(int[] fruits) {
        this.fruits = fruits;
        int[] classify = new int[]{-1, -1};
        int[] num = new int[2];
        int ans = 0;

        int len = fruits.length;
        for (int i = 0; i < len; ++i) {
            if (fruits[i] == classify[0]) {
                ++num[0];
            } else if (fruits[i] == classify[1]) {
                ++num[1];
            } else {
                if (i == 0) {
                    classify[0] = fruits[i];
                    ++num[0];
                } else {
                    int idx = (fruits[i - 1] == classify[0] ? 1 : 0);
                    classify[idx] = fruits[i];
                    num[idx] = 1;
                    num[idx ^ 1] = getPreNum(i, fruits[i - 1]);
                }
            }
            ans = Math.max(num[0] + num[1], ans);
        }
        return ans;
    }

    public int getPreNum(int curIdx, int classifyId) {
        int num = 0;
        for (int i = curIdx - 1; i >= 0; --i) {
            if (fruits[i] == classifyId) {
                ++num;
            } else {
                break;
            }
        }
        return num;
    }

    @Test
    public void test1() {
        int[] fruits;

        fruits = new int[]{1,2,1};
        System.out.println(this.totalFruit(fruits));

        fruits = new int[]{0,1,2,2};
        System.out.println(this.totalFruit(fruits));

        fruits = new int[]{1,2,3,2,2};
        System.out.println(this.totalFruit(fruits));

        fruits = new int[]{3,3,3,1,2,1,1,2,3,3,4};
        System.out.println(this.totalFruit(fruits));

        fruits = new int[]{1,0,1,4,1,4,1,2,3};
        System.out.println(this.totalFruit(fruits));
    }
}
